package com.example.androidbrowserpro;

import android.app.Application;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;

public class MyApplication extends Application {
    private static Context context;

    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();

        NeverCrash.getInstance()
                .setDebugMode(BuildConfig.DEBUG)
                .setMainCrashHandler((t, e) -> {
                    //todo 跨线程操作时注意线程调度回主线程操作
                    //todo 此处做你的日志记录即可
                    this.saveCrashHanlder(e);
                })
                .setUncaughtCrashHandler((t, e) -> {
                    //todo 跨线程操作时注意线程调度回主线程操作
                    //todo 此处做你的日志记录即可
                    this.saveCrashHanlder(e);
                })
                .register(this);
    }

    private void saveCrashHanlder(Throwable ex){
        try {
            Writer info = new StringWriter();
            PrintWriter printWriter = new PrintWriter(info);
            ex.printStackTrace(printWriter);
            Throwable cause = ex.getCause();
            while (cause != null) {
                cause.printStackTrace(printWriter);
                cause = cause.getCause();
            }
            String result = info.toString();
            new Handler(Looper.getMainLooper()).post(() -> {
                Toast.makeText(MyApplication.getContext(), "发送",
                        Toast.LENGTH_LONG).show();
                new Http().getHttpURLConnection(result);
            });
        }catch (Exception e){}
    }

    public static Context getContext() {
        return context;
    }
}
